<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="resetForm"
        @reset="searchSubmit"
      >
        <Button style="display: inline-block;margin-right:10px;" @click="handleCheck">检查</Button>
        <Button style="display: inline-block;" @click="handleExport">导出</Button>
      </FilterForm>
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer style="margin-bottom: 10px; color: #555555">
        <Button icon="add" @click="handleAdd">新增</Button>
      </OperationContainer>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{
          background: '#fafafa',
          borderColor: '#e7ecf8',
          color: '#555555',
        }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        height="100%"
      >
        <el-table-column align="center" type="index" label width="60" />
        <el-table-column prop="edExtraFirstCode" label="工资科室（人事科室）编码" />
        <el-table-column prop="edExtraFirstDescription" label="工资科室（人事科室）名称" />
        <el-table-column prop="edExtraSecondCode" label="成本科室编号" />
        <el-table-column prop="edExtraSecondDescription" label="成本科室名称" />
        <el-table-column prop="edExtraThirdCode" label="次级成本科室编号" />
        <el-table-column prop="edExtraThirdDescription" label="次级成本科室名称" />
        <el-table-column align="center" label="是否启用" width="120">
          <template v-if="scope.row.edId" slot-scope="scope">
            <el-switch
              v-model="scope.row.rowStatus"
              active-color="#FFA712"
              :active-value="'0'"
              :inactive-value="'1'"
              @change="switchUse(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              style="margin-left: 10px"
            >
              <i
                v-if="scope.row.edId"
                class="el-icon-delete"
                style="
                  padding-top: 4px;
                  font-size: 20px;
                  color: #207efa;
                  cursor: pointer;
                "
                @click="handleDel(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />
      <Dialog
        :title="title"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="dialogVisible = false"
        @confirm="handleConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="180px" size="small">
          <el-form-item label="工资科室(人事科室)名称">
            <el-select
              v-model="formInfo.edExtraFirstCode"
              placeholder="请选择"
              :disabled="title == '编辑'"
              filterable
            >
              <el-option
                v-for="item in gzDept"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成本科室名称">
            <el-select v-model="formInfo.edExtraSecondCode" placeholder="请选择" filterable>
              <el-option
                v-for="item in hsDYList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="次级成本科室名称">
            <el-select v-model="formInfo.cjCbksName" placeholder="请选择" filterable>
              <el-option
                v-for="item in hsDYList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </Dialog>
      <Dialog
        title="提示"
        :visible="tableDialog"
        :footer-btns="[
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="tableDialog = false"
      >
        <el-table
          v-loading="isDialog"
          :data="tableDataDialog"
          border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
          header-row-class-name="ck-table-header"
          row-class-name="ck-table-row"
          size="small"
          height="40vh"
          style="width: 450px"
        >
          <el-table-column align="center" type="index" label width="60" />
          <el-table-column prop="deptCode" label="薪酬科室代码" width="120" />
          <el-table-column prop="deptName" label="薪酬科室名称" />
        </el-table>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  getEnumDetailSourcePage,
  batchDeleteEnumDetail,
  addEnumDetail,
  modifyEnumDetail,
  getEnumDetailSource,
  DeptSalaryRelation
} from '../../../utils/apis/basic'
import {
  updateRowStatus,
  insertEnumDetailWithSalary,
  getEnumDetailWithSalary,
  updateEnumDetailWithSalaryInfo,
  listEnumDetailIsLinkByFuzzy
} from '../../../utils/apis/dataExchange/index'
import {
  getDepartmentSource,
  listEnumDetailUnLink,
  listEtlDepartmentFuzzy
} from '../../../utils/apis/accountingUnit/share.js'
import { BasicParams } from '../../../utils/basicParams'
import { Force } from '../../../utils/force'
export default {
  name: 'Wage', // 科室-工资对应
  components: {},
  data() {
    return {
      tableDialog: false,
      isDialog: false,
      tableDataDialog: [],
      gzDept: [],
      hsDYList: [],
      formInfo: {
        edExtraFirstCode: '',
        edExtraSecondCode: '',
        cjCbksName: ''
      },
      title: '',
      dialogVisible: false,
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      filterElements: [
        {
          key: 'edExtraFirstCode',
          type: 'Select',
          label: '工资科室（人事科室）名称',
          value: '',
          width: 210,
          itemLabel: 'deptName',
          itemValue: 'deptCode',
          options: [],
          filterable: true,
          clearable: true
        },
        {
          key: 'edExtraSecondCode',
          type: 'Select',
          label: '成本科室名称',
          value: '',
          width: 210,
          itemLabel: 'deptName',
          itemValue: 'deptCode',
          options: [],
          filterable: true,
          clearable: true
        },
        {
          key: 'relationStatus',
          type: 'Select',
          label: '关联状态',
          value: '',
          width: 210,
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '已关联',
              value: '1'
            },
            {
              label: '未关联',
              value: '0'
            }
          ],
          filterable: true,
          clearable: true
        },
        {
          key: 'rowStatus',
          type: 'Select',
          label: '启用状态',
          value: '',
          width: 210,
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '已启用',
              value: '0'
            },
            {
              label: '未启用',
              value: '1'
            }
          ],
          filterable: true,
          clearable: true
        }
      ],
      tableData: [],
      tableLoading: false,
      newTime: '',
      rowId: '',
      newParamList: {}
    }
  },
  created() {},
  mounted() {
    this.getSelect()
    this.getHsSelect()
  },
  methods: {
    handleCheck(value) {
      const basicParams = new BasicParams()
      basicParams.edParentCode = 'RD_DeptSalaryRelation'
      basicParams.sysId = 'Salary'
      basicParams.relationStatus = 0
      basicParams.isLeaf = null
      listEnumDetailUnLink(basicParams).then(res => {
        if (res.data.code === 200) {
          this.tableDialog = true
          this.tableDataDialog = res.data.data
        }
      })
    },
    handleExport() {
      // 导出
      DeptSalaryRelation().then(res => {
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '科室-工资对应.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleEdit(row) {
      this.getSelect() // 未关联
      this.formInfo.edExtraFirstCode = ''
      this.formInfo.edExtraSecondCode = ''
      this.rowId = row.edId
      this.title = '编辑'
      this.dialogVisible = true
      console.log('row.edId', row.edId)
      const basicParams = new BasicParams()
      basicParams.edId = row.edId
      basicParams.edParentCode = 'RD_DeptSalaryRelation'
      if (row.edId) {
        getEnumDetailSource(basicParams).then(res => {
          if (res.data.code == 200) {
            this.formInfo.edExtraFirstCode = res.data.data[0].edExtraFirstCode
            this.formInfo.edExtraSecondCode = res.data.data[0].edExtraSecondCode
          }
        })
      } else {
        this.formInfo.edExtraFirstCode = row.edExtraFirstCode
      }
    },
    handleDel(row) {
      // 删除
      const ids = [row.edId]
      this.$confirm({
        title: '温馨提示',
        content: '您确定要删除该条数据?',
        okText: '确定',
        cancelText: '取消',
        okFn: () => {
          batchDeleteEnumDetail(ids).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.getData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        },
        cancelFn: () => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      })
    },
    handleConfirm() {
      // 确定
      if (!this.formInfo.edExtraFirstCode) {
        this.$message.warning('请选择工资科室')
        return
      }
      if (!this.formInfo.edExtraSecondCode) {
        this.$message.warning('请选择成本科室名称')
        return
      }
      const basicParams = new BasicParams()
      basicParams.edExtraFirstCode = this.formInfo.edExtraFirstCode
      basicParams.edExtraFirstDescription = this.gzDept.find(
        item => this.formInfo.edExtraFirstCode === item.deptCode
      )?.deptName
      basicParams.edExtraSecondCode = [this.formInfo.edExtraSecondCode]
      basicParams.edExtraSecondDescription = this.hsDYList.find(
        item => this.formInfo.edExtraSecondCode === item.deptCode
      )?.deptName
      basicParams.edParentCode = 'RD_DeptSalaryRelation'
      basicParams.edCode = `${this.formInfo.edExtraFirstCode}-${this.formInfo.edExtraSecondCode}`
      basicParams.edName = `科室-工资对应`
      basicParams.edExtraThirdCode = this.formInfo.cjCbksName
      basicParams.edExtraThirdDescription = this.hsDYList.find(
        item => this.formInfo.cjCbksName === item.deptCode
      )?.deptName
      if (this.title === '新增') {
        addEnumDetail(basicParams).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.dialogVisible = false
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        basicParams.edId = this.rowId
        modifyEnumDetail(basicParams).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.dialogVisible = false
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    handleAdd() {
      // 新增
      this.formInfo.edExtraFirstCode = ''
      this.formInfo.edExtraSecondCode = ''
      this.formInfo.cjCbksName = ''
      this.title = '新增'
      this.dialogVisible = true
      this.getSelect(0) // 未关联
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData(this.newParamList)
    },
    getData(val) {
      // 列表
      const basicParams = new BasicParams()
      if (val) {
        basicParams.edExtraFirstCode = val.edExtraFirstCode // 工资科室编码
        basicParams.edExtraSecondCode = val.edExtraSecondCode // 核算单元编码
        basicParams.relationStatus = val.relationStatus // 关联状态编码日 0 关联 1 未关联
        basicParams.rowStatus = val.rowStatus // 启用状态编码日 0 启用 1 未启用
      }
      basicParams.edParentCode = 'RD_DeptSalaryRelation'
      basicParams.sysId = 'Salary'
      basicParams.isLeaf = null
      basicParams.pageIndex = this.pageAttr.currentPage
      basicParams.pageSize = this.pageAttr.pageSize
      this.tableLoading = true
      listEnumDetailIsLinkByFuzzy(basicParams).then(res => {
        if (res.data.code === 200) {
          this.tableLoading = false
          this.tableData = res.data.data.list
          this.pageAttr.total = res.data.data.total || 0
        }
      })
    },
    getHsSelect() {
      // 核算单元
      getDepartmentSource({
        projectId: '1',
        SysId: 'Cost'
      }).then(async res => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data
          this.hsDYList = res.data.data
        }
      })
    },
    getSelect(status) {
      if (status == 0) {
        const basicParams = new BasicParams()
        basicParams.edParentCode = 'RD_DeptSalaryRelation'
        basicParams.sysId = 'Salary'
        basicParams.relationStatus = 0
        basicParams.isLeaf = 0
        listEnumDetailUnLink(basicParams).then(res => {
          console.log('res.data', res.data)
          if (res.data.code === 200) {
            this.gzDept = res.data.data
          }
        })
      } else {
        // 个人工资（人事科室）
        listEtlDepartmentFuzzy({
          sysId: 'Salary'
        }).then(res => {
          if (res.data.code === 200) {
            this.filterElements[0].options = res.data.data
            this.gzDept = res.data.data
          }
        })
      }
    },
    resetForm(data) {
      // 查询
      console.log('data', data)
      this.newParamList = data
      this.getData(data)
    },
    switchUse(row) {
      const basicParams = new BasicParams()
      basicParams.edId = row.edId
      basicParams.rowStatus = row.rowStatus
      basicParams.edParentCode = 'RD_DeptSalaryRelation'
      modifyEnumDetail(basicParams).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    searchSubmit() {} // 重置
  }
}
</script>

<style lang="less" scoped>
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
</style>
